const svgCaptcha = require('svg-captcha');
const { ValidationError } = require("../utils/errors");

// 创建二维码
exports.createCaptcha = () => {
    return svgCaptcha.create({
        size: 6,
        ignoreChars: '0o1ilIO',
        noise: 2,
        color: true,
        background: '#2d3a4b'
    });
}

// 两个验证码是否相等
/**
 * 验证验证码
 * @param {String} serviceCaptcha 服务器保存的验证码 
 * @param {String} clientCaptcha 客户端传递进来的验证码
 * @returns 验证成功返回true，错误则抛出错误
 */
exports.validationCaptcha = (req) => {
    // console.log(req.session.captchaText, req.body.captcha.toLocaleLowerCase());
    // 1. 记录结果
    let result = false;
    // 2. 如果都存在才进行验证
    if (req.session.captchaText && req.body.captcha) {
        result = req.session.captchaText.toLocaleLowerCase() === req.body.captcha.toLocaleLowerCase();
        // 验证过一次之后清空服务器保存的验证码
        req.session.captchaText = "";
    }

    // 3. 如果经历上面代码还是为false的话，则抛出错误
    if(!result) {
        throw new ValidationError("验证码错误");
    }
}